package com.kk.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.common.lang.Result;
import com.kk.entity.User;
import com.kk.jwt.JwtTokenUtil;
import com.kk.jwt.JwtUser;
import com.kk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功操作
 * @author K. L. Mao
 * @create 2019/1/15
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserService userService;

    /**
     * 登录成功后将用户信息返回至前端 ,token放在header中
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //将用户信息传至前端
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        User user = userService.getOne(new QueryWrapper<User>().eq("username", jwtUser.getUsername()));
        user.setLastLogin(new Date());
        userService.updateById(user);
        //将用户信息存放至SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(jwtUser);
        renderToken(httpServletResponse,token,jwtUser);
    }

    /**
     * 渲染返回 token 页面,因为前端页面接收的都是Result对象，故使用application/json返回
     *
     * @param response
     * @throws IOException
     */
    public void renderToken(HttpServletResponse response, String token,JwtUser jwtUser) throws IOException {
        response.setHeader("Authorization",token);
        response.setHeader("Access-control-Expose-Headers","Authorization");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        jwtUser.setPassword("");
        response.getWriter().print(JSON.toJSONString(Result.success(200,"登录成功",jwtUser)));
    }
}